package api

import (
	"net/http"

	"gitee.com/zatto/project/tree/master/vblog/api/apps/user"
	"github.com/gin-gonic/gin"
)

func (h *handler) Login(c *gin.Context) {
	req := user.NewLoginRequestFromBasicAuth(c.Request)
	sess, err := h.svc.Login(c.Request.Context(), req)
	if err != nil {
		// 返回异常
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    http.StatusUnauthorized,
			"message": err.Error(),
		})
		return
	}

	// 给浏览器设置cookie(紧浏览器有效)
	c.SetCookie("username", sess.UserName, 60*60, "", "", false, false)
	c.SetCookie("session", sess.Id, 60*60, "", "", false, false)

	// 返回成功
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": sess,
	})
}

func (h *handler) Logout(c *gin.Context) {
	req := user.NewLogoutRequest()
	err := c.BindJSON(req)
	// 返回请求参数异常
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    http.StatusBadRequest,
			"message": err.Error(),
		})
		return
	}

	// 返回业务异常
	err = h.svc.Logout(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    http.StatusInternalServerError,
			"message": err.Error(),
		})
		return
	}

	// 返回成功
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "logout ok",
	})
}
